package ar.com.tallerdos.smartdinner.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import ar.com.tallerdos.smartdinner.model.Product;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private Dao<Product, Integer> productDao = null;
	private RuntimeExceptionDao<Product, Integer> productRuntimeDao = null;
	
	protected static final String DATABASE_NAME = "smartDinnerKitchen.db";
	protected static final int DATABASE_VERSION = 1;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	/**
	 * Close the database connections and clear any cached DAOs.
	 */
	@Override
	public void close() {
		super.close();
		productDao = null;
		productRuntimeDao = null;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		createTableOfClass(Product.class);
	}
	
	private void createTableOfClass(Class<?> clazz) {
		try {
			Log.i(clazz.getName(), "onCreate");
			TableUtils.createTable(connectionSource, clazz);
		} catch (SQLException e) {
			Log.e(clazz.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
			int oldVersion, int newVersion) {
		dropTableOfClass(Product.class);
		onCreate(db, connectionSource);
	}
	
	private void dropTableOfClass(Class<?> clazz) {
		try {
			Log.i(clazz.getName(), "onUpgrade");
			TableUtils.dropTable(connectionSource, clazz, true);
		} catch (SQLException e) {
			Log.e(clazz.getName(), "Can't drop database", e);
			throw new RuntimeException(e);
		}
	}

	public Dao<Product, Integer> getProductDao() throws SQLException {
		if (productDao == null) {
			productDao = getDao(Product.class);
		}
		return productDao;
	}

	public RuntimeExceptionDao<Product, Integer> getProductRuntimeExceptionDao() {
		if (productRuntimeDao == null) {
			productRuntimeDao = getRuntimeExceptionDao(Product.class);
		}
		return productRuntimeDao;
	}
}
